package com.lzj.demo.collection.list;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

public class ListDistinctDemo {
    /**
     * 初始化容器
     * */
    public List<String> initList = Arrays.asList(
            "吕布",
            "马超",
            "马超",
            "夏洛特",
            "夏侯惇",
            "项羽",
            "夏侯惇",
            "马超",
            "吕布",
            "廉颇"
    );
    /**
     * for 循环添加去重
     * @author: kaikaiking
     */
    @Test
    public void distinct1() {
        List<String> list = new ArrayList(initList);
        List<String> resultList = new ArrayList<>();
        for (String element : list) {
            if (!resultList.contains(element)) {
                resultList.add(element);
            }
        }
        System.out.println(resultList);
    }

    /**
     * for 双循环去重
     * @author: kaikaiking
     */
    @Test
    public void distinct2() {
        List<String> list = new ArrayList(initList);
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        System.out.println(list);
    }


    /**
     * for 循环重复坐标去重
     * @author: kaikaiking
     */
    @Test
    public void distinct3() {
        List<String> list = new ArrayList(initList);
        List<String> list2 = new ArrayList(initList);
        for (String element : list2) {
            if (list.indexOf(element) != list.lastIndexOf(element)) {
                list.remove(list.lastIndexOf(element));
            }
        }
        System.out.println(list);
    }

    /**
     * Set 去重
     * @author: kaikaiking
     */
    @Test
    public void distinct4() {
        List<String> list = new ArrayList(initList);
        List<String> resultList = new ArrayList(new LinkedHashSet(list));
        System.out.println(resultList);
    }

    /**
     * Stream 去重
     * @author: kaikaiking
     */
    @Test
    public void distinct5() {
        List<String> list = new ArrayList(initList);
        list = list.stream().distinct().collect(Collectors.toList());
        System.out.println(list);
    }
}
